﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using 作业2.Models;

namespace 作业2.Controllers
{
    public class TodoItemsController : ApiController
    {
        // 模拟数据库的静态列表
        private static readonly List<TodoItem> _todoItems = new List<TodoItem>();
        private static int _nextId = 1;

        // GET: api/TodoItems
        public IEnumerable<TodoItem> Get()
        {
            return _todoItems;
        }

        // GET: api/TodoItems/5
        public IHttpActionResult Get(int id)
        {
            var item = _todoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
                return NotFound();
            return Ok(item);
        }

        // POST: api/TodoItems
        public IHttpActionResult Post([FromBody] TodoItem item)
        {
            if (item == null)
                return BadRequest("无效的数据");

            item.Id = _nextId++;
            item.CreatedAt = DateTime.Now;
            _todoItems.Add(item);
            return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
        }

        // PUT: api/TodoItems/5
        public IHttpActionResult Put(int id, [FromBody] TodoItem updated)
        {
            var item = _todoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
                return NotFound();

            item.Title = updated.Title;
            item.Description = updated.Description;
            item.DueDate = updated.DueDate;
            return Ok(item);
        }

        // DELETE: api/TodoItems/5
        public IHttpActionResult Delete(int id)
        {
            var item = _todoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
                return NotFound();

            _todoItems.Remove(item);
            return Ok();
        }
    }
}